<template>
  <storeDiy ref="storeDiyRef" @save="saveClick" back ></storeDiy>
</template>
<script lang="ts">
export default {
  name: "storeDiyPageCreare",
};
</script>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import storeDiy from "@/components/diy/index.vue";
import {
  createDiyPage,
  updateDiyPage,
  getDiyPageDetail
} from "@/api/store/diy_page";
import { diyToolsType, Result, ResultError } from "@/types";
import { useRouter } from "vue-router";
const router = useRouter();

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const saveClick = (diyData: any) => {
  if (pageId.value == 0) {
    createDiyPage({
      page_data: diyData,
    })
      .then((res: Result) => {
        $utils.successMsg(res.message);
        setTimeout(() => {
          router.push({
            path: "/store/diy/page/list",
          });
          proxy?.$refs["storeDiyRef"]?.resetBtn();
        }, 1000);
      })
      .catch((err: ResultError) => {
        $utils.errorMsg(err);
        proxy?.$refs["storeDiyRef"]?.resetBtn();
      });
  } else {
    updateDiyPage({
      page_data: diyData,
      id: pageId.value,
    })
      .then((res: Result) => {
        $utils.successMsg(res.message);
        setTimeout(() => {
          router.push({
            path: "/store/diy/page/list",
          });
          proxy?.$refs["storeDiyRef"]?.resetBtn();
        }, 1000);
      })
      .catch((err: ResultError) => {
        $utils.errorMsg(err);
        proxy?.$refs["storeDiyRef"]?.resetBtn();
      });
  }
};

const pageId = ref<number | string>(0);

const pageData = ref<any>([]);

const toInit = () => {
  if (pageId.value == 0) {
    proxy?.$refs["storeDiyRef"]?.refreshDiyData(true);
    return false;
  }
  getDiyPageDetail({
    id: pageId.value,
  })
    .then((res: Result) => {
      // pageData.value = res.data.page_data;
      proxy?.$refs["storeDiyRef"]?.refreshDiyData(false, res.data.page_data);
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

onMounted(() => {
  let query = router.currentRoute.value.query;
  if (query && query.id) {
    pageId.value = String(query.id);
  }
  toInit();
});
</script>